import React, { Component } from 'react';
import PropTypes from "prop-types";
import {
    Text,
    Image,
    View,
    StyleSheet,
    TouchableHighlight,
    Animated,
    Easing,
    ScrollView,
    Platform,
    Dimensions
    } from 'react-native';

import TextElement from '../../components/text/Text';
import Color from '../../config/theme/standard/color';

import {getTabsStyle} from './TabsStyle'
import Variables from '../../config/theme/styles/index';

export default class Tab extends Component {
    constructor(props) {
        super(props);
        this.state = {
            width: 0,
            prevPropsData: props.tabData,
            data: props.tabData,
            isShowContent: props.isShowContent,
            isWideScreen: false,
            flag: false
        };
        this.flag = false;//如果能够以屏显示完整为false，否则为true
        this.centerIndex = -1;//记录当前选中项的索引
        this.len = 0;//一屏最多显示的个数
        this.startXAnimate = this.startXAnimate.bind(this);
        this.startYAnimate = this.startYAnimate.bind(this);

    }


    setIsWideScreen = () => {
        const screenWidth = Dimensions.get('window').width;
        if (screenWidth) {
            this.setState({
                isWideScreen: screenWidth > 500 && screenWidth < 800
            })
        }
    }
    
    componentDidMount() {
        // 适配鸿蒙折叠屏动态更新组件
        this.addEventListenerScreenWidth = Dimensions.addEventListener('change', this.setIsWideScreen)
        const wrapperWidth = this.props.wrapperWidth ? this.props.wrapperWidth : Dimensions.get('window').width

        const data = this.state.data;
        const totalWidth = data.length * this.props.tabItemWidth;
        let width = 0;
        let lastWidth = wrapperWidth - 30
        //通过判断tab的总的长度和屏幕宽度的关系，来确定是均分还是写死宽度
        if (totalWidth < lastWidth && this.props.tabPosition!="left") {
            width = lastWidth / data.length;
            this.flag = false;
        } else {
            width = this.props.tabItemWidth;
            this.flag = true;
            this.len = Math.floor(lastWidth / this.props.tabItemWidth);
        };
        this.setState({ width: width ,flag: this.flag})
    }
    componentWillUnmount() {
        // 适配鸿蒙折叠屏动态更新组件
        if (this.addEventListenerScreenWidth) {
            this.addEventListenerScreenWidth = null
        }
    }

    static getDerivedStateFromProps(nextProps, prevState) {

        if(('tabData' in nextProps) && ( nextProps.tabData !== prevState.prevPropsData)){
            const data = nextProps.tabData;
            // 折叠屏适配，保证wrapperWidth未传入页面展示正常
            const wrapperWidth = nextProps.wrapperWidth ? nextProps.wrapperWidth : Dimensions.get('window').width
            const totalWidth = data.length * nextProps.tabItemWidth;;
            let width = 0;
            let lastWidth = wrapperWidth - 30
            let flag = false
            //通过判断tab的总的长度和屏幕宽度的关系，来确定是均分还是写死宽度 , 这个只有tab为横向布局时使用
            if (totalWidth < lastWidth) {
                width = lastWidth / data.length;
                this.flag = false;
                flag = false
            } else {
                width = nextProps.tabItemWidth;
                this.flag = true;
                flag = true
                this.len = Math.floor(lastWidth / nextProps.tabItemWidth);
            };
            
            return {
                flag: this.flag,
                width: width,
                prevPropsData: nextProps.tabData,
                data: nextProps.tabData
            }
        } else {
            const data = nextProps.tabData;
            const wrapperWidth = nextProps.wrapperWidth ? nextProps.wrapperWidth : Dimensions.get('window').width
            const totalWidth = data.length * nextProps.tabItemWidth;;
            let width = 0;
            let lastWidth = wrapperWidth - 30
            let flag = false
            //通过判断tab的总的长度和屏幕宽度的关系，来确定是均分还是写死宽度 , 这个只有tab为横向布局时使用
            if (totalWidth < lastWidth) {
                width = lastWidth / data.length;
                this.flag = false;
                flag = false
            } else {
                width = nextProps.tabItemWidth;
                this.flag = true;
                flag = true
                this.len = Math.floor(lastWidth / nextProps.tabItemWidth);
            };
            return {
                flag: this.flag,
                width: width,
            }
        }
        return null;
    }

    _selectTo() {
        const wrapperWidth = this.props.wrapperWidth ? this.props.wrapperWidth : Dimensions.get('window').width
        const data = this.state.data;
        let y = 0;
        let x = 0;
        let lastWidth = wrapperWidth - 30
        
        if (this.state.flag) {
            //初始话时应该显示的位置
            if (this.props.tabPosition == "left") {
                if (this.centerIndex >= 2) {
                    if (this.centerIndex == data.length - 1) {
                        y=-this.props.height * (data.length - 4);
                    } else {
                        y=-(this.centerIndex - 2) * this.props.height;
                    }
                } else {
                    y=0;
                };
            } else if (this.props.tabPosition == "top" || this.props.tabPosition == "bottom") {
                if (this.centerIndex >= this.len) {
                    x=-(this.centerIndex - 1) * this.props.tabItemWidth-15;
                } else {
                    x=0;
                };
                for (var i = 1; i < this.len; i++) {
                    if (this.centerIndex == this.state.data.length - i) {//处理结尾
                        x=lastWidth- this.props.tabItemWidth * this.state.data.length;
                    };
                };
                ;
            };
        };
        if(this._ScrollView) {
            this._ScrollView.scrollTo({y: y,x:-x, animated: false});
        };
    }

    //水平方向滚动
    startXAnimate(index) {
        const wrapperWidth = this.props.wrapperWidth ? this.props.wrapperWidth : Dimensions.get('window').width
        let lastWidth = wrapperWidth - 30
        
        if (this.state.flag) {
            let x = 0;
            if (index == 0) {//处理开头
                x = 0;
            } else {
                x = -this.props.tabItemWidth * (index - 1)-15;
            };
            //一屏最多显示4个的时候，处理最后四个显示位置
            for (var i = 1; i < this.len; i++) {
                if (index == this.state.data.length - i) {//处理结尾
                    x = lastWidth - this.props.tabItemWidth * this.state.data.length
                };
            };
            if(this._ScrollView) {
                this._ScrollView.scrollTo({x:-x, animated: true});
            };
        };
    };

    //垂直方向滚动
    startYAnimate(index) {
        if (this.flag) {
            let y = 0;
            if (index < 2) {//处理开头两个
                y = 0;
            } else if (index == this.state.data.length - 1 || index == this.state.data.length - 2) {//处理结尾两个
                y = -this.props.height * (this.state.data.length - 3)
            } else {
                y = -(index-1 ) * this.props.height;
            }
            if(this._ScrollView) {
                this._ScrollView.scrollTo({y:-y, animated: true});
            };
        };
    };

    closeContent=()=>{
        this.setState({
            isShowContent: false
        });
    }
    getCurrentIndex=()=>{
        return this.centerIndex
    }

    tabClick = (event, key, index) => {
        let data_key = key;
        //回掉函数
        if (typeof this.props.eventClick === "function") {
            this.props.eventClick(data_key);
        };
        //通过tabPosition不同执行不同方向的动画
        if (this.props.tabPosition == "top" || this.props.tabPosition == "bottom") {
            this.startXAnimate(index);
        } else if (this.props.tabPosition == "left") {
            this.startYAnimate(index);
        };
        if(this.state.data[index].hasArrow){
            let isShow = false;
            if (this.centerIndex != index) {
                isShow = true;
            } else {
                isShow = this.props.isdblClick ? !this.state.isShowContent : this.state.isShowContent;
            }
            ;
            this.setState({
                data: this.state.data.map(function (ele) {
                    if (ele.key === key) {
                        ele.active = true;
                    } else {
                        ele.active = false;
                    }
                    return ele;
                }),
                isShowContent: isShow
            });
        }else{
            this.setState({
                data: this.state.data.map(function (ele) {
                    if (ele.key === key) {
                        ele.active = true;
                    } else {
                        ele.active = false;
                    }
                    return ele;
                })
            });
        }
    };

    _renderLine = ()=>{
        let { activeLinePosition } = this.props
        let content = ""
        if(activeLinePosition =="bottom"){
            content=  <View style={{height:2,width:20,backgroundColor:"#CF0000",position:"absolute",bottom:5,borderRadius:3}}></View>
        }else if(activeLinePosition =="top"){
            content=  <View style={{height:2,width:20,backgroundColor:"#CF0000",position:"absolute",bottom:5,borderRadius:3}}></View>
        }else if(activeLinePosition =="right"){
            content=  <View style={{height:20,width:2,backgroundColor:"#CF0000",position:"absolute",right:-6,borderRadius:3}}></View>
        }else {
            content=  <View></View>
        }
       return content
    }

    render() {
        let { styles,TabsStyle} = getTabsStyle(Variables); 
        const _this = this;
        const {
            themeColor,
            padding,
            radius,
            height,
            backgroundColor,
            backgroundHeight,
            borderColor,
            type,
            tabPosition,
            activeLinePosition,
            hasActiveLine,
            // wrapperWidth,
            tabItemWidth,
            elementLeft
        } = this.props;
        
        const wrapperWidth = this.props.wrapperWidth ? this.props.wrapperWidth : Dimensions.get('window').width
        // console.log('wrapperWidth', wrapperWidth);
        
        const flexContainerStyles = [styles.flexContainer];//外层容器样式
        const headerTabBtnStyles = [styles.headerTabBtn];//所有tab样式
        const headerTabBtnActiveStyles = [styles.headerTabBtnActive];//选中项样式
        const tabContainerStyles = [];
        const realBorderColor = borderColor ? borderColor :( themeColor ? themeColor : TabsStyle.themeColor) ;

        let tabContainerWidth = 0;//横向时列表的宽度
        let tabContainerHeight = height ? height: TabsStyle.TabsHeight;//纵向时列表的高度
        let bgContainerHeight = backgroundHeight;//背景的高度

        let borderBottomColor = realBorderColor;
        let borderTopColor = realBorderColor;
        let borderRightColor = realBorderColor;
        let borderLeftColor = realBorderColor;
    
        let borderBottomWidth = 2;
        let borderTopWidth = 0;
        let borderLeftWidth = 0;
        let borderRightWidth = 0;

        let color = themeColor ? themeColor : TabsStyle.activeBottomColor;
        let borderWidth = type !== 'linear' ? 0 : TabsStyle.activeBorderWidth;
        if(tabPosition=="left"){
            borderRightColor="#fff"
        }

        //默认只有底部边框，被选中项的边框宽度及颜色
        if(hasActiveLine){
            if (activeLinePosition == 'top') {
                borderTopWidth = borderWidth;
                borderTopColor = color;
                borderBottomColor = "#fff";
                borderBottomWidth=2;
            } else if (activeLinePosition == 'bottom') {
                borderBottomWidth = borderWidth;
                borderBottomColor = color;
            } else if (activeLinePosition == 'right' && tabPosition=="left") {
                borderRightWidth = borderWidth;
                borderRightColor = color;
                borderBottomColor="#fff";
                borderBottomWidth=borderWidth;
            }
        };

        //选中状态时，边线、宽度、高度的设置
        if (tabPosition == "left") {
            tabContainerHeight = (height ? height : TabsStyle.TabsHeight)  * this.state.data.length;
            if (_this.flag) {
                bgContainerHeight = (height ? height : TabsStyle.TabsHeight)  * 3;
                if(Platform.OS === 'web'){
                    tabContainerHeight = (height ? height : TabsStyle.TabsHeight)  * 3;
                }
            } else {
                bgContainerHeight = (height ? height : TabsStyle.TabsHeight )  * this.state.data.length
            }
            ;
            tabContainerWidth = tabItemWidth;
            borderBottomWidth = 0;
        } else if (tabPosition == "top" || tabPosition == "bottom") {
            if (_this.state.flag) {
                tabContainerWidth = tabItemWidth * this.state.data.length;
            } else {
                tabContainerWidth = wrapperWidth - 30;
            }
            tabContainerHeight = height ? height : TabsStyle.TabsHeight ;
        }
        //容器样式
        flexContainerStyles.push({
            height: bgContainerHeight,
            paddingHorizontal: padding,
            backgroundColor: backgroundColor,
            width: wrapperWidth // 适配鸿蒙容器宽度
        });
        //tab样式
        tabContainerStyles.push({
            width: tabContainerWidth,
            flexDirection: tabPosition == "left" ? 'column' : 'row',
            height: tabContainerHeight ,
            backgroundColor:Color.white
        })
    
        //非选中项样式
        headerTabBtnStyles.push({
            height: height || TabsStyle.TabsHeight,
            // borderColor: realBorderColor,
            borderColor: 'transparent',
            borderBottomWidth: borderBottomWidth,
            borderBottomColor: this.props.hasBorder ? "#fff" : backgroundColor,
            borderRightColor:'#fff',
            borderTopWidth: borderTopWidth,
            borderRightWidth: borderRightWidth,
        });
        
        //选中项样式
        headerTabBtnActiveStyles.push({
            height: height || TabsStyle.TabsHeight,
            borderBottomColor: borderBottomColor,
            borderBottomWidth: borderBottomWidth,
            borderRightWidth: borderRightWidth,
            borderRightColor: borderRightColor,
            borderTopWidth: borderTopWidth,
            borderTopColor: borderTopColor,
            borderLeftWidth: borderLeftWidth,
            borderLeftColor: borderLeftColor,
            borderBottomRightRadius:TabsStyle.activeRadius,
            borderBottomLeftRadius:TabsStyle.activeRadius,
            backgroundColor: type !== 'linear' ? ( themeColor ?  themeColor : TabsStyle.themeColor ) : '#ffffff'
        });
        if(elementLeft == 'center'){
            headerTabBtnStyles.push({
                alignItems: 'center',
            });
            headerTabBtnActiveStyles.push({
                alignItems: 'center',
            });
        }
        const data = _this.state.data;
       
        const tabList = data.map(function (element, index) {
            let borderLeftRadius = '';
            let borderRightRadius = '';
            //拿到当前选中项的下标
            for (var i = 0; i < data.length; i++) {
                if (data[i].active) {
                    _this.centerIndex = i;
                };
            };

            if(activeLinePosition == 'right'){
                borderRightRadius={borderRightWidth:2}
            };

            //设置tab的样式
            let headerTab = element.active ? headerTabBtnActiveStyles : headerTabBtnStyles;
            const textColor = element.active ? type !== 'linear' ? styles.textColorActive : {color: themeColor ? themeColor:TabsStyle.activeTextColor} :  {color: TabsStyle.normalTextColor};
            const textFontSize =  element.active ? TabsStyle.activeTextFontSize : TabsStyle.normalTextFontSize;
            const textFontWeight =  element.active ? TabsStyle.activeTextFontWeight : TabsStyle.normalTextFontWeight;

            //通过参数hasArrow来判断是否显示右边箭头
            let imgComponent;
            if(element.hasArrow){
                if(element.active){
                    if(_this.state.isShowContent){
                        imgComponent = <Image source={require('../../assets/tabs_arrow_up_red.png')} style={{width:16,height:16,marginLeft:4}}/>;
                    }else{
                        imgComponent = <Image source={require('../../assets/tabs_arrow_down_red.png')} style={{width:16,height:16,marginLeft:4}}/>;
                    }
                }else{
                    imgComponent = <Image source={require('../../assets/tabs_arrow_down_black.png')} style={{width:16,height:16,marginLeft:4}}/>;
                }
            }else if(element.img){
                imgComponent = <Image source={element.img} style={{width:16,height:16,marginLeft:4}}/>
            }
            
            if(element.hasArrow && element.img){
                imgComponent = <Image source={element.img} style={{width:16,height:16,marginLeft:4}}/>
            }

            //2023.9.28 增加一个分支,通过tab的位置处理下划线
            if(tabPosition!="left"){
                 //设置tab的样式
                 headerTab = headerTabBtnStyles;
                return (
                    <TouchableHighlight key={element.key}
                                        underlayColor={'white'}
                                        style={[headerTab,{width:_this.state.width},borderLeftRadius,borderRightRadius]}
                                        onPress={(event)=>{_this.tabClick(event, element.key, index)}}>
                        <View style={{position:"relative",flexDirection:"column",justifyContent:"center",alignItems:"center"}}>
                            <View style={{flex:1, flexDirection: 'row',alignItems: 'center'}}>
                                {/* {imgElement} */}
                                <TextElement text={element.text} numberOfLines={1}  customStyle={[textColor,{fontSize:textFontSize,fontWeight:textFontWeight},_this.props.textStyle]} align={'center'}/>
                                {imgComponent}
                              
                            </View>
                            {
                                element.active && hasActiveLine ?  _this._renderLine(): <View></View>
                            }
                        </View>
                    </TouchableHighlight>
                );
            }else {
                return (
                    <TouchableHighlight key={element.key}
                                        underlayColor={'white'}
                                        style={[headerTab,{width:_this.state.width},borderLeftRadius,borderRightRadius,]}
                                        onPress={(event)=>{_this.tabClick(event, element.key, index)}}>
                        <View style={{flex:1, flexDirection: 'row',alignItems: 'center'}}>
                            {/* {imgElement} */}
                            <TextElement text={element.text} numberOfLines={1}  customStyle={[textColor,{fontSize:textFontSize,fontWeight:textFontWeight},_this.props.textStyle]} align={'center'}/>
                            {imgComponent}
                        </View>
                    </TouchableHighlight>
                );
            }
        
           
        });

        //生成内容
        const activeTabContent = data.map(function (element, index) {
            const Content = element.tabContent;
            if (element.active && Content) {
                return React.isValidElement(Content)
                    ? Content
                    : <Content key="content"/>;
            }
        });
        //根据tabPosition来设置tab和内容的位置
        let content = null;
     
        if (tabPosition == 'top') {
            content = <View>
                <View style={[flexContainerStyles,{height:height || TabsStyle.TabsHeight,alignItems:'center',flexDirection:'row'}]}>
                    <View style={{height:height || TabsStyle.TabsHeight,width:15,borderBottomColor: this.props.hasBorder ?"#fff" : backgroundColor,borderBottomWidth:type=="linear"?2:0}}/>
                    <ScrollView
                        bounces={false}
                        horizontal={this.state.flag}
                        iosalwaysBounceHorizontal={false}
                        iosalwaysBounceVertical={false}
                        showsHorizontalScrollIndicator={false}
                        onLayout = {() => this._selectTo()}
                        ref = {(e) => this._ScrollView = e}
                        style={{height: height || TabsStyle.TabsHeight}}
                    >
                        <View style={[tabContainerStyles]}>
                            {tabList}
                        </View>
                    </ScrollView>
                    <View style={{height:height ||TabsStyle.TabsHeight,width:15,borderBottomColor: this.props.hasBorder ?"#fff" : backgroundColor,borderBottomWidth:type=="linear"?2:0}}/>
                </View>
                {_this.state.isShowContent ? activeTabContent : null}
            </View>
        } else if (tabPosition == 'bottom') {
            content = <View>
                {_this.state.isShowContent ? activeTabContent : null}
                <View style={flexContainerStyles}>
                    <ScrollView
                        bounces = {false}
                        horizontal ={this.flag}
                        iosalwaysBounceHorizontal={false}
                        iosalwaysBounceVertical={false}
                        showsHorizontalScrollIndicator={false}
                        onLayout = {() => this._selectTo()}
                        ref = {(e) => this._ScrollView = e}
                    >
                        <View style={tabContainerStyles}>
                            {tabList}
                        </View>
                    </ScrollView>
                </View>
            </View>
        } else if (tabPosition == 'left') {
            content = <View style={{flexDirection:'row',height:bgContainerHeight}}>
                <View>
                    <ScrollView
                        bounces = {false}
                        showsVerticalScrollIndicator={false}
                        onLayout = {() => this._selectTo()}
                        ref = {(e) => this._ScrollView = e}
                        style={{height:bgContainerHeight}}
                    >
                        <Animated.View style={[tabContainerStyles]}>
                            {tabList}
                        </Animated.View>
                    </ScrollView>
                </View>
                <View style={{flex:1}}>
                    {_this.state.isShowContent ? activeTabContent : null}
                </View>
            </View>
        }
        ;
        return (
            <View style={{flex:1,alignItems:'center'}}>
                {content}
            </View>
        )
    }
}
Tab.propTypes = {
    tabData: PropTypes.array,
    eventClick: PropTypes.func,
    //条式的还是标签式的
    type: PropTypes.oneOf(['primary', 'linear']),
    //tab的主题颜色
    themeColor: PropTypes.string,
    //tab的圆角大小
    radius: PropTypes.number,
    //到两边的距离
    padding: PropTypes.number,
    //背景的高度
    backgroundHeight: PropTypes.number,
    //背景的颜色
    backgroundColor: PropTypes.string,
    //tab的高度
    height: PropTypes.number,
    //没选中tab边框颜色
    borderColor: PropTypes.string,
    //字体内容部分的封装
    textStyle: Text.propTypes.style,
    //是否有分割线
    hasRightBorder: PropTypes.bool,
    //是否展示内容
    isShowContent: PropTypes.bool,
    //是否可以双击控制能容的显示与隐藏
    isdblClick: PropTypes.bool,
    //tab的位置
    tabPosition: PropTypes.oneOf(['top', 'bottom', 'left']),
    //选中项的边线位置
    activeLinePosition: PropTypes.oneOf(['top', 'bottom', 'right']),
    //选中项是否有边线
    hasActiveLine:PropTypes.bool,
    //
    isUpdate:PropTypes.bool,
    // 横屏展示时才用到该属性
    wrapperWidth:PropTypes.number,
    // 每个item的宽度
    tabItemWidth:PropTypes.number,
    hasBorder:PropTypes.bool,
    //配置文字左对齐
    elementLeft:PropTypes.string
}
Tab.defaultProps = {
    type: 'linear',
    radius: 8,
    backgroundHeight: 45,
    backgroundColor:Color.tabs.background,
    padding:0,
    tabPosition: 'top',
    activeLinePosition: 'bottom',
    isShowContent: true,
    isdblClick:false,
    hasActiveLine:true,
    isUpdate: true,
    tabItemWidth: 100,
    hasBorder: true,
    elementLeft: 'center'
}

